<?php

declare(strict_types=1);

namespace App\Model;

use App\Utils\FunUtil;

/**
 * @property int $id
 * @property string $ip
 * @property string $remark 备注信息
 * @property string $create_time 添加时间
 */
class AuditIp extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'tb_audit_ip';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer'];


    /**
     * Note - 记录审核环境用户ip
     * DateTime 2024/7/29 15:57
     * User Admin
     * @param $uid
     * @param $channel
     * @return true
     */
    public static function recordIp($uid = 0, $channel = '')
    {
        $ip = FunUtil::getClientIp();
        // 判断ip是否在白名单中
        $white = AuditIpWhite::query()->where("ip", $ip)->first();
        if (!empty($white)) {
            return true;
        }

        $ip1 = explode(".", $ip);
        $ip1 = $ip1[0] . "." . $ip1[1];

        if (!(new self())->isAuditIp($ip) && !in_array($ip1, ['116.22', '116.23'])) {
            (new self())->insert([
                'ip' => $ip,
                'remark' => "渠道：{$channel} " . ($uid ? "审核环境登录用户，ID：{$uid}" : ''),
                'create_time' => date("Y-m-d H:i:s")
            ]);
        }
        return true;

    }

    // 是否审核IP
    public function isAuditIp($ip)
    {
        $rs = $this->query()->where('ip', $ip)->exists();
        if ($rs) {
            // 是审核IP
            return true;
        }
        return false;

    }


    /**
     * 判断ip是否在审核白名单中
     * @param $ip
     * @return bool
     */
    public function isWhiteIp($ip)
    {
        // 判断ip是否在白名单中
        $exists = AuditIpWhite::query()->where("ip", $ip)->exists();
        if ($exists) {
            return true;
        }
        return false;
    }


}
